import { ref } from 'vue'
import { categoryList, categoryAdd, categoryEdit, categoryDel } from '../http/category'

export function useCategoryData() {
  const treeData = ref<any[]>([])
  const searchKey = ref('')
  
  //将数据变成树状 - 使用 parentId 构建
  function listToTree(list: any[]) {
    const map: Record<string, any> = {}
    const roots: any[] = []
    
    // 1. 创建映射表
    list.forEach(item => {
      map[item.objectId] = { ...item, children: [] }
    })
    
    // 2. 构建树形结构
    list.forEach(item => {
      if (!item.parentId || item.parentId === '') {
        // 根节点
        roots.push(map[item.objectId])
      } else {
        // 子节点
        const parent = map[item.parentId]
        if (parent) {
          parent.children.push(map[item.objectId])
        } else {
          // 如果找不到父节点，作为根节点处理
          roots.push(map[item.objectId])
        }
      }
    })
    return roots
  }

  //数据列表的显示
  async function fetchCategoryList() {
    try {
      const response = await categoryList(searchKey.value || undefined)
      let results = response.data.results
      treeData.value = listToTree(results)
    } catch (error) {
      console.error('获取分类列表失败:', error)
    }
  }

  //数据删除
  async function deleteCategory(objectId: string) {
    try {
      await categoryDel(objectId)
      await fetchCategoryList()
      return true
    } catch (error) {
      console.error('删除分类失败:', error)
      throw error
    }
  }

  return {
    treeData,
    searchKey,
    fetchCategoryList,
    deleteCategory
  }
}